#include "lvgl/lvgl.h"
#include "lvgl/src/indev/lv_indev.h"
#include <unistd.h>
#include <pthread.h>
#include <time.h>
#include <stdio.h>
#include <stdlib.h>

#include <pthread.h>

#include "../deepseek-client/ai_client.h"
#include "../deepseek-client/context.h"
#include "../deepseek-client/history.h"

static const char *getenv_default(const char *name, const char *dflt)
{
    return getenv(name) ?: dflt;
}
// 配置当前显示器
#if LV_USE_LINUX_FBDEV
lv_display_t *disp;
static void lv_linux_disp_init(void)
{
    const char *device = getenv_default("LV_LINUX_FBDEV_DEVICE", "/dev/fb0");
    disp = lv_linux_fbdev_create();

    lv_linux_fbdev_set_file(disp, device);
}
#elif LV_USE_LINUX_DRM
static void lv_linux_disp_init(void)
{
    const char *device = getenv_default("LV_LINUX_DRM_CARD", "/dev/dri/card0");
    lv_display_t *disp = lv_linux_drm_create();

    lv_linux_drm_set_file(disp, device, -1);
}
#elif LV_USE_SDL

static void lv_linux_disp_init(void)
{
    const int width = atoi(getenv("LV_SDL_VIDEO_WIDTH") ?: "800");
    const int height = atoi(getenv("LV_SDL_VIDEO_HEIGHT") ?: "480");

    lv_sdl_window_create(width, height);
}
#else
#error Unsupported configuration
#endif

QM_P queue;

char context[3][1024];

int client_fd;

// 主容器
lv_obj_t *cont;
// 左容器
lv_obj_t *cont_left;
// 右容器上容器
lv_obj_t *cont_left_up;
// 左容器上容器标签
lv_label_t *logo_label;
// 左容器上容器按钮标签
lv_label_t *btn_label;
// 左容器下容器
lv_obj_t *cont_left_down;
// 左容器下容器中历史记录
lv_obj_t *btnm;
// 右容器
lv_obj_t *cont_right;
// 右容器文本框
lv_textarea_t *textarea;
// 右容器键盘
lv_keyboard_t *keyboard;
// 键盘拼音插件
lv_ime_pinyin_t *pingyin;
// 右边聊天框聊天标签存放容器
lv_obj_t *cont_right_content;

lv_label_t *response_label;

lv_button_t *new_chat_but;

lv_button_t *del_btn;

lv_button_t *send_bt;

// ================================ other
extern lv_pinyin_dict_t dict[];

extern cJSON *history_json_object;

char data[1024 * 10];

// 表示当前聊天标题
char current_title[100] = {};

// 历史记录标题
char *titles[100] = {};

// 历史记录内容
char (*question_content)[1024 * 1];
char (*response_content)[1024 * 10];

// char *history_map[100] = {"历史记录1", "\n","历史记录2", "\n","历史记录3", "\n","历史记录4", "\n","历史记录5",""};

pthread_mutex_t mutex; // lvgl保护临界资源

char keyboard_ready_input_flag = 1;

// 滚动到聊天框最底部
static void chat_scroll_to_down(char flag)
{
    // 滚动使回复可见
    // lv_obj_scroll_to_view(response_label, LV_ANIM_ON);
    if (flag == 1)
        lv_obj_scroll_to_y(cont_right_content, LV_COORD_MAX, LV_ANIM_ON); // 启用动画
    else
        lv_obj_scroll_to_y(cont_right_content, LV_COORD_MAX, LV_ANIM_OFF); // 不启用动画
}

static void content_printf(char *content)
{
    strcat(data, content);
    pthread_mutex_lock(&mutex);
    /* lvgl操作 */

    lv_label_set_text(response_label, data);

    chat_scroll_to_down(1);

    pthread_mutex_unlock(&mutex);
    // printf("%s", content);
}

static void *chat(void *arg)
{
    // 设置分离属性
    pthread_detach(pthread_self());

    memset(data, 0, sizeof(data)); // 清空上一次的回复

    pthread_mutex_lock(&mutex);

    lv_obj_remove_flag(del_btn, LV_OBJ_FLAG_HIDDEN);

    lv_buttonmatrix_set_button_ctrl_all(btnm, LV_BUTTONMATRIX_CTRL_DISABLED);

    // 不允许键盘确认输入
    keyboard_ready_input_flag = 0;

    // 不允许新建话题和删除话题
    lv_obj_add_state(new_chat_but, LV_STATE_DISABLED);
    lv_obj_add_state(del_btn, LV_STATE_DISABLED);

    pthread_mutex_unlock(&mutex);

    client_chat_context(client_fd, arg, queue->size, content_printf);

    pthread_mutex_lock(&mutex);

    lv_buttonmatrix_clear_button_ctrl_all(btnm, LV_BUTTONMATRIX_CTRL_DISABLED);

    // 允许键盘确认输入
    keyboard_ready_input_flag = 1;

    // 回答完成后允许话题新建和删除
    lv_obj_remove_state(new_chat_but, LV_STATE_DISABLED);
    lv_obj_remove_state(del_btn, LV_STATE_DISABLED);

    pthread_mutex_unlock(&mutex);

    // 一次对话处理完 开始记录历史记录
    history_init();
    static char title[1024] = {};
    if ((queue->size == 1) && (strcmp(current_title, "new_topic") == 0)) // 没有标题的对话初始标题为第一个问题 新开的也设置为第一个标题
    {
        strcpy(current_title, queue->data[queue->tail]);
        // 将内容设置到历史记录标题上
        for (int i = 0; i < 100; i++)
        {
            if (strcmp(titles[i], "new_topic") == 0)
            {
                strcpy(titles[i], queue->data[queue->tail]);
                pthread_mutex_lock(&mutex);
                lv_buttonmatrix_set_map(btnm, titles);
                pthread_mutex_unlock(&mutex);
            }
        }
    }

    history_set(current_title, queue->data[queue->tail], data);
    history_close();

    // 取消线程
    pthread_cancel(pthread_self());
}

// ================================ lvgl

static void textarea_cb(lv_event_t *e)
{
    lv_event_code_t code = lv_event_get_code(e);
    lv_obj_t *textarea = lv_event_get_target(e);
    lv_obj_t *kb = lv_event_get_user_data(e);

    lv_keyboard_set_textarea(kb, textarea);

    if (code == LV_EVENT_FOCUSED)
    {
        lv_obj_remove_flag(kb, LV_OBJ_FLAG_HIDDEN);
        lv_obj_align_to(textarea, kb, LV_ALIGN_OUT_TOP_MID, -30, 0);
        lv_obj_align_to(send_bt, textarea, LV_ALIGN_OUT_RIGHT_MID, 10, 0);

        lv_obj_set_height(cont_right_content, 170);

        chat_scroll_to_down(0);
    }
    if (code == LV_EVENT_DEFOCUSED)
    {
        lv_obj_add_flag(kb, LV_OBJ_FLAG_HIDDEN);
        lv_obj_align(textarea, LV_ALIGN_BOTTOM_MID, -30, 0);
        lv_obj_align_to(send_bt, textarea, LV_ALIGN_OUT_RIGHT_MID, 10, 0);

        lv_obj_set_height(cont_right_content, 340);

        chat_scroll_to_down(0);
    }
}

static void btn_label_call_back(lv_event_t *e)
{
    if (strcmp(lv_label_get_text(btn_label), "<") == 0)
    {
        lv_label_set_text(btn_label, ">");
        lv_obj_add_flag(logo_label, LV_OBJ_FLAG_HIDDEN);
        lv_obj_add_flag(cont_left_down, LV_OBJ_FLAG_HIDDEN);
        lv_obj_set_flex_grow(cont_right, 10); // 4显示历史记录（展开边框） 10不显示历史记录（收起边框）
        lv_obj_align_to(send_bt, textarea, LV_ALIGN_OUT_RIGHT_MID, 10, 0);

    }
    else
    {
        lv_label_set_text(btn_label, "<");
        lv_obj_remove_flag(logo_label, LV_OBJ_FLAG_HIDDEN);
        lv_obj_remove_flag(cont_left_down, LV_OBJ_FLAG_HIDDEN);
        lv_obj_set_flex_grow(cont_right, 4); // 4显示历史记录（展开边框） 10不显示历史记录（收起边框）
        lv_obj_align_to(send_bt, textarea, LV_ALIGN_OUT_RIGHT_MID, 10, 0);

    }
}

static void keyboard_ready_call_back(lv_event_t *e)
{
    if (keyboard_ready_input_flag == 0) // 为0不允许输入 这个处理并不好 最好用其他处理方法
        return;

    if (strcmp(lv_textarea_get_text(textarea), "") == 0) // 内容为空不允许提问
        return;
    if (strcmp(lv_textarea_get_text(textarea), "\n") == 0) // 内容为换行不允许提问
        return;

    lv_event_code_t code = lv_event_get_code(e);
    if (code == LV_EVENT_READY || code == LV_EVENT_CLICKED)
    {
        lv_label_t *question_label = lv_label_create(cont_right_content); // 问题标签
        lv_obj_set_style_bg_opa(question_label, 255, 0);
        lv_obj_set_style_bg_color(question_label, lv_color_make(200, 200, 200), 0);
        lv_obj_set_style_radius(question_label, 5, 0);
        lv_obj_set_style_pad_all(question_label, 10, 0);
        lv_label_set_text(question_label, lv_textarea_get_text(textarea));
        // 通过文字长度获取label宽度
        lv_point_t text_size;
        lv_txt_get_size(&text_size, lv_textarea_get_text(textarea), &lv_font_montserrat_20, 0, 0, 1000, 0);
        // printf("%d\n",text_size.x);
        if (text_size.x > lv_obj_get_width(cont_right_content) * 0.7)
            lv_obj_set_width(question_label, LV_PCT(70));

        // 创建线程处理问题
        response_label = lv_label_create(cont_right_content); // 回复标签
        lv_label_set_text(response_label, "loading...");
        lv_obj_set_width(response_label, LV_PCT(100));

        en_queue(queue, lv_textarea_get_text(textarea));
        get_context(queue, context);
        pthread_t tid;
        pthread_create(&tid, NULL, chat, context);

        lv_textarea_set_text(textarea, "");
        // lv_obj_add_flag(keyboard, LV_OBJ_FLAG_HIDDEN);
        // lv_obj_align(textarea, LV_ALIGN_BOTTOM_MID, 0, 0);
    }
}

// 创建问题文字框
static void question_text(lv_obj_t *cont, char *text)
{
    lv_label_t *question_label = lv_label_create(cont); // 问题标签
    lv_obj_set_style_bg_opa(question_label, 255, 0);
    lv_obj_set_style_bg_color(question_label, lv_color_make(200, 200, 200), 0);
    lv_obj_set_style_radius(question_label, 5, 0);
    lv_obj_set_style_pad_all(question_label, 10, 0);
    lv_label_set_text(question_label, text);
    // 通过文字长度获取label宽度
    lv_point_t text_size;
    lv_txt_get_size(&text_size, lv_textarea_get_text(textarea), &lv_font_montserrat_20, 0, 0, 1000, 0);
    // printf("%d\n",text_size.x);
    if (text_size.x > lv_obj_get_width(cont_right_content) * 0.7)
        lv_obj_set_width(question_label, LV_PCT(70));
}
// 创建回复文字框
static void response_text(lv_obj_t *cont, char *text)
{
    lv_label_t *response_label = lv_label_create(cont); // 回复标签
    lv_obj_set_width(response_label, LV_PCT(100));
    lv_label_set_text(response_label, text);
}

static void btnm_event_cb(lv_event_t *e)
{
    lv_event_code_t code = lv_event_get_code(e);
    if (code == LV_EVENT_VALUE_CHANGED)
    {
        lv_obj_t *obj = lv_event_get_target(e);
        uint32_t id = lv_buttonmatrix_get_selected_button(obj);

        lv_buttonmatrix_set_button_ctrl_all(btnm, LV_BUTTONMATRIX_CTRL_CLICK_TRIG); // 设置点击才触发LV_EVENT_VALUE_CHANGED

        lv_buttonmatrix_set_button_ctrl(btnm, id, LV_BUTTONMATRIX_CTRL_CHECKED);

        // printf("%s\n",lv_buttonmatrix_get_button_text(obj,id));
        memset(question_content, 0, 1024 * 1 * 100);
        memset(response_content, 0, 1024 * 10 * 100);

        history_get_content_by_title(lv_buttonmatrix_get_button_text(obj, id), question_content, response_content);
        strcpy(current_title, lv_buttonmatrix_get_button_text(obj, id));
        // printf("%s\n", question_content);
        // printf("%s\n", response_content);

        // 清空聊天框
        lv_obj_clean(cont_right_content);

        // 清空上下文队列
        queue->size = 0;

        int index = 0;
        while (1)
        {
            if (strcmp(response_content[index], "") == 0)
                break;

            question_text(cont_right_content, question_content[index]);
            response_text(cont_right_content, response_content[index]);

            // 加载上下文
            en_queue(queue, question_content[index]);

            index++;
        }

        // 根据情况 向右部容器显示删除话题按钮
        if (strcmp(current_title, "new_topic") == 0)
            lv_obj_add_flag(del_btn, LV_OBJ_FLAG_HIDDEN);
        else
            lv_obj_remove_flag(del_btn, LV_OBJ_FLAG_HIDDEN);

        // 滚动到底部
        chat_scroll_to_down(0);
    }
}

void new_chat_but_call_back(lv_event_t *e)
{
    lv_event_code_t code = lv_event_get_code(e);
    if (code == LV_EVENT_CLICKED)
    {

        // 清空聊天框
        lv_obj_clean(cont_right_content);

        // 清空上下文队列
        queue->size = 0;

        strcpy(current_title, "new_topic");

        lv_obj_add_flag(del_btn, LV_OBJ_FLAG_HIDDEN);

        // 更新左侧历史列表
        int index = 0;
        while (1)
        {
            if (strcmp(titles[index], "") == 0)
            {

                if (index == 0) // 没有记录时特殊处理
                {
                    strcpy(titles[index], "new_topic");
                    strcpy(titles[index + 1], "");
                    index++;
                }
                else if (index == 1) // 只有一条记录时特殊处理
                {
                    strcpy(titles[index], "\n");
                    strcpy(titles[index + 1], "new_topic");
                    strcpy(titles[index + 2], "\n");
                    strcpy(titles[index + 3], "");
                    index += 3;
                }
                else
                {
                    strcpy(titles[index], "new_topic");
                    strcpy(titles[index + 1], "\n");
                    strcpy(titles[index + 2], "");
                    index += 2;
                }

                break;
            }
            else if (strcmp(titles[index], "new_topic") == 0) // 如果有new_topic则不允许再创建新话题 直接使用未使用的话题
            {
                index++;
                lv_buttonmatrix_set_button_ctrl(btnm, ((index - 1) / 2), LV_BUTTONMATRIX_CTRL_CHECKED); // 选择到未使用的新话题
                lv_obj_scroll_to_y(cont_left_down, LV_COORD_MAX, LV_ANIM_ON);                           // 使最下面的新话题按钮可见

                return;
            }

            index++;
        }

        lv_buttonmatrix_set_map(btnm, titles);

        lv_obj_set_size(btnm, LV_PCT(100), LV_PCT(index * 8)); // 一个选项占 8%

        lv_buttonmatrix_set_button_ctrl_all(btnm, LV_BUTTONMATRIX_CTRL_CHECKABLE);

        lv_buttonmatrix_set_one_checked(btnm, true);

        lv_buttonmatrix_set_button_ctrl(btnm, ((index - 1) / 2), LV_BUTTONMATRIX_CTRL_CHECKED);

        lv_obj_scroll_to_y(cont_left_down, LV_COORD_MAX, LV_ANIM_ON); // 使最下面的新话题按钮可见
    }
}

void del_btn_call_back(lv_event_t *e)
{
    history_del_by_title(current_title);

    history_close(); // 将更新存储到文本中

    history_get_title(titles); // 重新获取标题格式字符串

    // 更新侧边栏 到new_topic
    // 清空聊天框
    lv_obj_clean(cont_right_content);

    // 清空上下文队列
    queue->size = 0;

    strcpy(current_title, "new_topic");

    lv_obj_add_flag(del_btn, LV_OBJ_FLAG_HIDDEN);

    // 更新左侧历史列表
    int index = 0;
    while (1)
    {
        if (strcmp(titles[index], "") == 0)
        {

            if (index == 0) // 没有记录时特殊处理
            {
                strcpy(titles[index], "new_topic");
                strcpy(titles[index + 1], "");
                index++;
            }
            else if (index == 1) // 只有一条记录时特殊处理
            {
                strcpy(titles[index], "\n");
                strcpy(titles[index + 1], "new_topic");
                strcpy(titles[index + 2], "\n");
                strcpy(titles[index + 3], "");
                index += 3;
            }
            else
            {
                strcpy(titles[index], "new_topic");
                strcpy(titles[index + 1], "\n");
                strcpy(titles[index + 2], "");
                index += 2;
            }

            break;
        }
        else if (strcmp(titles[index], "new_topic") == 0) // 如果有new_topic则不允许再创建新话题 直接使用未使用的话题
        {
            index++;
            lv_buttonmatrix_set_button_ctrl(btnm, ((index - 1) / 2), LV_BUTTONMATRIX_CTRL_CHECKED); // 选择到未使用的新话题
            return;
        }

        index++;
    }

    lv_buttonmatrix_set_map(btnm, titles);

    lv_obj_set_size(btnm, LV_PCT(100), LV_PCT(index * 8)); // 一个选项占 8%

    lv_buttonmatrix_set_button_ctrl_all(btnm, LV_BUTTONMATRIX_CTRL_CHECKABLE);

    lv_buttonmatrix_set_one_checked(btnm, true);

    lv_buttonmatrix_set_button_ctrl(btnm, ((index - 1) / 2), LV_BUTTONMATRIX_CTRL_CHECKED);

    lv_obj_scroll_to_y(cont_left_down, LV_COORD_MAX, LV_ANIM_ON); // 使最下面的新话题按钮可见
}

// 支持中文字体样式
lv_style_t hei_font_style;
// 新主题给指定控件添加样式
static void new_theme_apply_cb(lv_theme_t *th, lv_obj_t *obj)
{
    if (lv_obj_check_type(obj, &lv_label_class) || lv_obj_check_type(obj, &lv_textarea_class))
    {
        lv_obj_add_style(obj, &hei_font_style, LV_STATE_DEFAULT);
    }
}

int main(void)
{
    lv_init();
    /*Linux display device init*/
    lv_linux_disp_init();

    printf("init input\n");
#if LV_USE_SDL
    // init input device sdl2
    lv_sdl_mouse_create();
    lv_sdl_keyboard_create();
    lv_sdl_mousewheel_create();
#elif LV_USE_LINUX_FBDEV
    // touch
    lv_indev_t *touch = lv_evdev_create(LV_INDEV_TYPE_POINTER, "/dev/input/event0");
    // 默认行为 默认与活动的(最后创建的)disp绑定，如果创建新的disp也需要将输入设备与其绑定才能在新disp上输入
    // lv_indev_set_display(touch, disp);
    lv_evdev_set_calibration(touch, 0, 0, 1024, 600); // 说明输入设备的尺寸是1024,600的大小 其会根据大小自动适应显示屏大小 如果驱动和硬件层面没有设置的话就由软件层面设置
#endif
    printf("init input  end\n");

    //========================== 字体样式
    // 中文字体样式测试 使用freetype库 使用有中文字模的字库ttf 创建字体样式对象 对需要使用字体的对象设置样式style
    lv_font_t *hei_font = lv_freetype_font_create("/usr/share/fonts/simhei.ttf", LV_FREETYPE_FONT_RENDER_MODE_BITMAP, 14, LV_FREETYPE_FONT_STYLE_NORMAL);
    lv_font_t *hei_font_20 = lv_freetype_font_create("/usr/share/fonts/simhei.ttf", LV_FREETYPE_FONT_RENDER_MODE_BITMAP, 20, LV_FREETYPE_FONT_STYLE_NORMAL);

    // lv_style_t hei_font_style;
    lv_style_init(&hei_font_style);
    lv_style_set_text_font(&hei_font_style, hei_font);
    lv_style_set_text_align(&hei_font_style, LV_TEXT_ALIGN_LEFT);

    // 设置默认主题
    // 1.获取默认主题
    lv_theme_t *default_theme = lv_theme_get_from_obj(NULL);
    // 2.设置追加的主题
    lv_theme_t append_theme = *default_theme;
    lv_theme_set_parent(&append_theme, default_theme);
    lv_theme_set_apply_cb(&append_theme, new_theme_apply_cb);
    // 3.将主题应用在显示器上
    lv_disp_set_theme(NULL, &append_theme);
    //=========================

    // 界面布局
    cont = lv_obj_create(lv_screen_active());
    lv_obj_set_size(cont, 800, 480);
    lv_obj_set_style_pad_all(cont, 0, 0);

    // 1.横向
    lv_obj_set_flex_flow(cont, LV_FLEX_FLOW_ROW);

    // 1.1左列表容器
    cont_left = lv_obj_create(cont);
    lv_obj_set_height(cont_left, LV_PCT(100));
    lv_obj_set_style_pad_all(cont_left, 0, 0);
    lv_obj_set_flex_grow(cont_left, 1);

    // 左列表容器竖向
    lv_obj_set_flex_flow(cont_left, LV_FLEX_FLOW_COLUMN);

    // lv_obj_add_flag(cont_left,LV_OBJ_FLAG_HIDDEN);
    // 1.1.1商标 迪普吸克
    cont_left_up = lv_obj_create(cont_left);
    lv_obj_set_width(cont_left_up, LV_PCT(100));
    lv_obj_set_flex_grow(cont_left_up, 1);
    lv_obj_set_style_pad_all(cont_left_up, 0, 0);

    // 商标
    logo_label = lv_label_create(cont_left_up);
    lv_obj_set_height(logo_label, LV_PCT(100));
    lv_obj_set_style_pad_all(logo_label, 15, 0);
    lv_obj_set_style_text_font(logo_label, hei_font_20, 0);
    lv_label_set_text(logo_label, "deepseek");
    // lv_obj_add_flag(logo_label,LV_OBJ_FLAG_HIDDEN);

    // 边框按钮
    btn_label = lv_label_create(cont_left_up);
    lv_obj_align(btn_label, LV_ALIGN_RIGHT_MID, -10, 0);
    lv_obj_set_height(btn_label, LV_PCT(100));
    lv_obj_set_style_pad_all(btn_label, 15, 0);
    lv_obj_set_style_text_font(btn_label, hei_font_20, 0);
    lv_label_set_text(btn_label, "<");
    lv_obj_add_flag(btn_label, LV_OBJ_FLAG_CLICKABLE);
    lv_obj_add_event_cb(btn_label, btn_label_call_back, LV_EVENT_CLICKED, NULL);

    // 1.1.2历史记录菜单
    cont_left_down = lv_obj_create(cont_left);
    lv_obj_set_width(cont_left_down, LV_PCT(100));
    lv_obj_set_flex_grow(cont_left_down, 7);
    lv_obj_set_style_pad_all(cont_left_down, 0, 0);

    // 历史记录标题
    for (int i = 0; i < 100; i++)
        titles[i] = calloc(1, 100);
    // 历史记录内容 请求
    for (int i = 0; i < 100; i++)
        question_content = calloc(100, 1024 * 1);
    // 历史记录内容 回复
    for (int i = 0; i < 100; i++)
        response_content = calloc(100, 1024 * 10);

    // 获取历史记录标题
    history_init();

    history_get_title(titles);

    history_close();

    // 判断有多少个话题
    int top_num = 0;
    for (int i = 0; i < 100; i++)
    {
        if (strcmp(titles[i], "") == 0)
            break;
        top_num++;
    }
    // printf("top_num:%d\n",top_num);

    static lv_style_t style_bg;
    lv_style_init(&style_bg);
    lv_style_set_pad_all(&style_bg, 0);
    lv_style_set_pad_gap(&style_bg, 5);
    lv_style_set_clip_corner(&style_bg, true);
    lv_style_set_radius(&style_bg, LV_RADIUS_CIRCLE);
    lv_style_set_border_width(&style_bg, 0);
    lv_style_set_bg_opa(&style_bg, LV_OPA_0);

    static lv_style_t style_btn;
    lv_style_init(&style_btn);
    lv_style_set_border_width(&style_btn, 0);
    lv_style_set_bg_opa(&style_btn, 0);
    lv_style_set_radius(&style_btn, 10);
    lv_style_set_height(&style_btn, 30);
    lv_style_set_text_font(&style_btn, hei_font);

    btnm = lv_buttonmatrix_create(cont_left_down);

    lv_buttonmatrix_set_map(btnm, titles);
    lv_obj_add_style(btnm, &style_bg, 0);
    lv_obj_add_style(btnm, &style_btn, LV_PART_ITEMS);
    lv_obj_add_event_cb(btnm, btnm_event_cb, LV_EVENT_VALUE_CHANGED, NULL);
    // 根据标题数设置高度
    lv_obj_set_size(btnm, LV_PCT(100), LV_PCT(top_num * 8)); // 一个选项占 8%

    /*Allow selecting on one number at time*/
    lv_buttonmatrix_set_button_ctrl_all(btnm, LV_BUTTONMATRIX_CTRL_CHECKABLE);

    lv_buttonmatrix_set_one_checked(btnm, true);
    // lv_buttonmatrix_set_button_ctrl(btnm, 1, LV_BUTTONMATRIX_CTRL_CHECKED);

    // 1.2右边聊天框容器
    cont_right = lv_obj_create(cont);
    lv_obj_set_height(cont_right, LV_PCT(100));
    lv_obj_set_flex_grow(cont_right, 4); // 4显示历史记录（展开边框） 10不显示历史记录（收起边框）

    // 1.2.1右边聊天框聊天标签存放容器
    cont_right_content = lv_obj_create(cont_right);
    lv_obj_set_size(cont_right_content, LV_PCT(100), 340);

    // 聊天标签容器竖向
    lv_obj_set_flex_flow(cont_right_content, LV_FLEX_FLOW_COLUMN);

    lv_obj_set_flex_align(cont_right_content, LV_FLEX_ALIGN_START, LV_FLEX_ALIGN_END, LV_FLEX_ALIGN_END); // 右对齐

    // 用户文字气泡在右侧
    // lv_label_t *temp_label = lv_label_create(cont_right_content);
    // lv_obj_set_style_bg_opa(temp_label, 255, 0);
    // lv_obj_set_style_bg_color(temp_label, lv_color_make(200, 200, 200), 0);
    // lv_obj_set_style_radius(temp_label, 5, 0);
    // lv_obj_set_style_pad_all(temp_label, 10, 0);
    // lv_obj_set_width(temp_label, LV_PCT(70));
    // lv_label_set_text(temp_label, "hifaefjaewjfaolweijfioa;wjfeasfaaf");

    // response_label = lv_label_create(cont_right_content);
    // lv_label_set_text(response_label, "hi");
    // lv_obj_set_width(response_label, LV_PCT(100));

    // // 1.2.2右边聊天框容器开启新对话按钮
    new_chat_but = lv_button_create(cont_right);
    lv_obj_set_size(new_chat_but, 100, 30);
    lv_obj_align_to(new_chat_but, cont_right_content, LV_ALIGN_OUT_BOTTOM_MID, 0, 5);
    lv_label_t *new_chat_but_label = lv_label_create(new_chat_but);
    lv_obj_center(new_chat_but_label);
    lv_label_set_text(new_chat_but_label, "开启新的对话");
    lv_obj_add_event_cb(new_chat_but, new_chat_but_call_back, LV_EVENT_CLICKED, NULL);

    del_btn = lv_button_create(cont_right);
    lv_obj_set_size(del_btn, 100, 30);
    lv_obj_align_to(del_btn, new_chat_but, LV_ALIGN_OUT_RIGHT_MID, 50, 0);
    lv_label_t *del_btn_label = lv_label_create(del_btn);
    lv_obj_center(del_btn_label);
    lv_label_set_text(del_btn_label, "删除该对话");
    lv_obj_add_event_cb(del_btn, del_btn_call_back, LV_EVENT_CLICKED, NULL);
    lv_obj_set_style_bg_color(del_btn, lv_color_make(255, 0, 0), 0);
    lv_obj_add_flag(del_btn, LV_OBJ_FLAG_HIDDEN);

    // 1.2.3右边聊天框容器输入文本框
    textarea = lv_textarea_create(cont_right);
    lv_obj_set_width(textarea, LV_PCT(90));
    lv_obj_set_height(textarea, 50);
    lv_obj_align(textarea, LV_ALIGN_BOTTOM_MID, -30, 0);
    // 1.2.4右边聊天框容器键盘
    keyboard = lv_keyboard_create(cont_right);
    lv_obj_add_flag(keyboard, LV_OBJ_FLAG_HIDDEN);
    // 1.2.5右边聊天框容器键盘拼音插件
    pingyin = lv_ime_pinyin_create(cont_right);
    lv_ime_pinyin_set_keyboard(pingyin, keyboard);
    lv_obj_set_style_text_font(pingyin, hei_font, 0);
    lv_ime_pinyin_set_dict(pingyin, dict);

    lv_obj_add_event_cb(textarea, textarea_cb, LV_EVENT_ALL, keyboard);
    lv_keyboard_set_textarea(keyboard, textarea);
    lv_obj_add_event_cb(keyboard, keyboard_ready_call_back, LV_EVENT_READY, NULL);

    send_bt = lv_button_create(cont_right);
    lv_obj_set_size(send_bt, 40, 40);
    lv_obj_align_to(send_bt, textarea, LV_ALIGN_OUT_RIGHT_MID, 10, 0);
    lv_label_t *send_bt_label = lv_label_create(send_bt);
    lv_obj_center(send_bt_label);
    lv_label_set_text(send_bt_label, LV_SYMBOL_GPS);
    lv_obj_set_style_text_font(send_bt_label, &lv_font_montserrat_24, 0);

    lv_obj_add_event_cb(send_bt, keyboard_ready_call_back, LV_EVENT_CLICKED, NULL);

    client_fd = client_init();

    // 聊天线程

    queue = init_queue_manage();

    pthread_mutex_init(&mutex, NULL);

    // ================================启动时直接添加一个新话题
    // 清空聊天框
    lv_obj_clean(cont_right_content);

    // 清空上下文队列
    queue->size = 0;

    strcpy(current_title, "new_topic");

    // 启动时创建一个新话题
    int index = 0;
    while (1)
    {
        if (strcmp(titles[index], "") == 0)
        {
            if (index == 0) // 没有记录时特殊处理
            {
                strcpy(titles[index], "new_topic");
                strcpy(titles[index + 1], "");
                index++;
            }
            else if (index == 1) // 只有一条记录时特殊处理
            {
                strcpy(titles[index], "\n");
                strcpy(titles[index + 1], "new_topic");
                strcpy(titles[index + 2], "\n");
                strcpy(titles[index + 3], "");
                index += 3;
            }
            else
            {
                strcpy(titles[index], "new_topic");
                strcpy(titles[index + 1], "\n");
                strcpy(titles[index + 2], "");
                index += 2;
            }
            lv_buttonmatrix_set_map(btnm, titles);

            lv_obj_set_size(btnm, LV_PCT(100), LV_PCT(index * 8)); // 一个选项占 8%

            break;
        }
        else if (strcmp(titles[index], "new_topic") == 0) // 如果有new_topic则不允许再创建新话题 直接使用未使用的话题
        {
            index++;
            break;
        }

        index++;
    }
    lv_buttonmatrix_set_button_ctrl_all(btnm, LV_BUTTONMATRIX_CTRL_CHECKABLE);

    lv_buttonmatrix_set_one_checked(btnm, true);

    lv_buttonmatrix_set_button_ctrl(btnm, ((index - 1) / 2), LV_BUTTONMATRIX_CTRL_CHECKED);

    lv_obj_scroll_to_y(cont_left_down, LV_COORD_MAX, LV_ANIM_ON); // 使最下面的新话题按钮可见

    while (1)
    {
        pthread_mutex_lock(&mutex);
        lv_timer_handler();
        pthread_mutex_unlock(&mutex);
        usleep(5000);
    }

    client_close(client_fd);
    return 0;
}
